import backgroundImg from '@/assets/images/background.png';
import Footer from '@/components/Footer';
import { getUserInfoById as queryCurrentUser } from '@/services/groupNumber';
import { dummyLogin } from '@/services/login';
import { getMenuList as queryMenu } from '@/services/menu';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import { history, useModel } from 'umi';
import { Alert, message, Tabs } from 'antd';
import { JSEncrypt } from 'jsencrypt';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};
const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<any>({});
  const [type, setType] = useState<string>('account');
  const [status, setStatus] = useState<string>('');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [currentUser, setCurrentUser] = useState<any>({});
  const [menuData, setMenuData] = useState<any>([]);
  const fetchUserInfo = async (userId: any) => {
    const userInfo = await queryCurrentUser({
      id: userId,
    });
    if (userInfo.code == '0') {
      const params = {
        roleId: userInfo.data.roleId,
      };
      const menuRes = await queryMenu(params);
      setCurrentUser(userInfo.data);
      setMenuData(menuRes.data);
      return {
        userInfo: userInfo.data,
        menuData: menuRes.data,
      };
    }
  };
  const handleSubmit = async (values: { username: string; password: string }) => {
    try {
      let encrypt = new JSEncrypt();
      encrypt.setPublicKey(Settings.pubilcKey + '');
      let password = encrypt.encrypt(values.password); //password为需要加密的字段
      const params = {
        username: values.username,
        password: password,
      };

      // 登录
      const msg = await dummyLogin(params);
      if (msg.code === '0') {
        // const defaultLoginSuccessMessage = '登录成功！';
        // message.success(defaultLoginSuccessMessage);
        //session 存储
        sessionStorage.setItem('userId', msg.data.id);
        sessionStorage.setItem('userToken', msg.data.token);
        const res = await fetchUserInfo(msg.data.id);
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: res.userInfo, menuData: res.menuData }));
        });
        const urlParams = new URL(window.location.href).searchParams;
        console.log(urlParams.get('redirect') || '/consultCenter/siteSearch');
        history.push(urlParams.get('redirect') || '/consultCenter/siteSearch');

        return;
      }
      // 如果失败去设置用户错误信息
      setStatus('error');
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        overflow: 'auto',
        backgroundImage: 'url(' + `${backgroundImg}` + ')',
        backgroundSize: '100% 100%',
      }}
    >
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          color: '#103289',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
            color: '#103289',
          }}
          logo={<img alt="logo" src="/logo_police.png" />}
          title="台管理系统"
          subTitle={' '}
          initialValues={{
            autoLogin: true,
          }}
          // actions={['其他登录方式 :', <ActionIcons key="icons" />]}
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            style={{
              color: '#103289',
            }}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
              // {
              //   key: 'mobile',
              //   label: '手机号登录',
              // },
            ]}
          />

          {status === 'error' && type === 'account' && (
            <LoginMessage content={'错误的用户名和密码'} />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'请输入用户名'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
            </>
          )}

          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码 ?
            </a>
            <a
              onClick={()=>{
                history.push({
                  pathname:'/user/login',
                });
              }}
              style={{
                float: 'right',
                marginRight:'15px'
              }}
            >
              证书登录
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
